﻿using System;
using System.IO;

namespace Sencha.Serialization
{
	public sealed class JsonStreamReader : JsonReaderBase
	{
		private StreamReader m_reader;


		public JsonStreamReader(Stream stream)
			: this(stream, new AdHocSerializer(), DefaultBufferSize)
		{

		}
		public JsonStreamReader(Stream stream, int bufferSize = DefaultBufferSize)
			: this(stream, new AdHocSerializer(), bufferSize)
		{

		}
		public JsonStreamReader(Stream stream, ISerializationContext context, int bufferSize = DefaultBufferSize)
			: base(context, bufferSize)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");
			if (!stream.CanRead)
				throw new Exceptions.UnreadableStream("stream");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_reader = new StreamReader(stream, context.Encoding);
		}

		protected override int FillBuffer(char[] buffer, int index)
		{
			if (buffer == null)
				throw new ArgumentNullException("buffer");
			if (index < 0 || index >= buffer.Length)
				throw new ArgumentOutOfRangeException("index");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			var count = buffer.Length - index;
			if (count <= 0)
				return index;

			var readed = m_reader.Read(buffer, index, count);
			return index + readed;
		}
	}
}
